﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;

namespace System.Controls.Converters
{
  [DebuggerStepThrough]
  [ContentProperty( "Converters" )]
  [ValueConversion( typeof( object ), typeof( object ) )]
  public class ValueConverterGroup : DependencyObject, IValueConverter
  {
    private static readonly DependencyPropertyKey _convertersPropertyKey =
      DependencyProperty.RegisterReadOnly( "Converters", typeof( Collection<IValueConverter> ),
        typeof( ValueConverterGroup ), new FrameworkPropertyMetadata() );

    public static readonly DependencyProperty ConvertersProperty = _convertersPropertyKey.DependencyProperty;

    public ValueConverterGroup()
    {
      Converters = new Collection<IValueConverter>();
    }

    public Collection<IValueConverter> Converters
    {
      get { return GetValue( ConvertersProperty ) as Collection<IValueConverter>; }
      private set { SetValue( _convertersPropertyKey, value ); }
    }

    public object Convert( object value, Type targetType, object parameter, CultureInfo culture )
    {
      var convertedValue = value;

      if ( Converters.Count == 0 )
        return DependencyProperty.UnsetValue;

      foreach ( var valueConverter in Converters )
        convertedValue = valueConverter.Convert( convertedValue, targetType, parameter, culture );

      return convertedValue;
    }

    public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture )
    {
      var convertedValue = value;

      if ( Converters.Count == 0 )
        return DependencyProperty.UnsetValue;

      for ( var i = Converters.Count - 1; i >= 0; --i )
        convertedValue = Converters[i].ConvertBack( convertedValue, targetType, parameter, culture );

      return convertedValue;
    }

  }
}
